package com.eudon.user.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.eudon.user.domain.entity.TbUser;
import com.eudon.user.domain.req.RegisterReq;
import com.eudon.user.enums.RespCode;
import com.eudon.user.enums.UserRole;
import com.eudon.user.exception.BusinessException;
import com.eudon.user.manager.UserOperationManager;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author eudon
 * @description 用户注册service
 * @date 2025/9/15
 * @email syd19970616@gmail.com
 * @address <a href="https://gitee.com/eudon">Gitee</a>
 */
@Service
public class UserRegisterService {
    @Resource
    private UserOperationManager manager;

    /**
     * 用户注册
     *
     * @param registerReq 用户注册信息
     * @return 是否成功
     */
    public Long register(RegisterReq registerReq) {

        checkParams(registerReq);

        String userName = registerReq.getUserName();
        String password = registerReq.getPassword();
        String email = registerReq.getEmail();
        TbUser tbUser = new TbUser();
        tbUser.setUserName(userName);
        tbUser.setUserAvatar(null);
        tbUser.setUserPassword(password);
        tbUser.setUserAccount(StrUtil.isBlank(email) ? registerReq.getPhone() : email);
        tbUser.setId(RandomUtil.randomLong());
        tbUser.setUserRole(UserRole.NORMAL_USER);
        if (!manager.registerOne(tbUser)) {
            throw new BusinessException(RespCode.SYSTEM_ERR0R);
        }

        return tbUser.getId();
    }

    private void checkParams(RegisterReq registerReq) {
        if (!StrUtil.equals(registerReq.getPassword(), registerReq.getConfirmPassword())) {
            throw new BusinessException(RespCode.PARAMS_ERROR.getCode(), "两次输入密码不一致");
        }
        if (StrUtil.isBlank(registerReq.getEmail()) && StrUtil.isBlank(registerReq.getPhone())) {
            throw new BusinessException(RespCode.PARAMS_ERROR.getCode(), "邮箱和手机号必输一项");
        }
    }
}
